package cc.sjfx.sharedoc.activity.examination;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.mandroid.frame.toast.MLog;
import cn.mandroid.frame.toast.MToast;
import cn.mandroid.frame.utils.ThreadUtils;
import cc.sjfx.sharedoc.R;
import cc.sjfx.sharedoc.activity.BasicActivity;
import cc.sjfx.sharedoc.bean.ExamShowListViewBean;
import cc.sjfx.sharedoc.cache.UserCache;
import cc.sjfx.sharedoc.db.ExamDB;
import cc.sjfx.sharedoc.db.bmob.Examination;
import cc.sjfx.sharedoc.fragment.BasicFragment;
import cc.sjfx.sharedoc.function.Preference;
import cc.sjfx.sharedoc.utils.CacheUtil;
import cc.sjfx.sharedoc.widget.adapter.MyPagerAdapter;
import cc.sjfx.sharedoc.widget.adapter.ExamXListViewAdapter;
import cc.sjfx.sharedoc.widget.adapter.PieceXListViewAdapter;
import cc.sjfx.sharedoc.widget.adapter.QuestionXListViewAdapter;
import cc.sjfx.sharedoc.widget.view.MyViewPager;
import cc.sjfx.sharedoc.widget.view.xlistview.XListView;
import cc.sjfx.sharedoc.widget.view.xlistview.XListView.IXListViewListener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;

public class HomeFragment extends BasicFragment implements IXListViewListener {
	private MyViewPager mPager;// 页卡内容
	private List<View> listViews; // Tab页面列表
	private ImageView cursor;// 动画图片
	private TextView t1, t2, t3;// 页卡头标
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度
	private XListView examXListView;
	private XListView questionXListView;
	private XListView pieceXListView;
	int screenHeight, screenWidth, lastX, lastY;
	ExamXListViewAdapter examAdapter;
	PieceXListViewAdapter pieceAdapter;
	QuestionXListViewAdapter questionAdapter;
	private Preference preference;
	private List<ExamShowListViewBean> examlist = new ArrayList<ExamShowListViewBean>();
	private List<ExamShowListViewBean> questionlist = new ArrayList<ExamShowListViewBean>();
	private List<ExamShowListViewBean> piecelist = new ArrayList<ExamShowListViewBean>();
	ReleaseComplete complete;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		preference = Preference.instance(context);
		IntentFilter filter = new IntentFilter();
		filter.addAction("releaseComplete");
		filter.addAction("finishDownload");
		complete = new ReleaseComplete();
		context.registerReceiver(complete, filter);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_home, container, false);
		InitImageView(view);
		initTextView(view);
		initViewPager(view);
		return view;
	}

	@Override
	public void onStart() {

		super.onStart();
	}

	private void initViewPager(View view) {
		// TODO Auto-generated method stub
		mPager = (MyViewPager) view.findViewById(R.id.vPager);
		listViews = new ArrayList<View>();
		LayoutInflater mInflater = ((getActivity())).getLayoutInflater();
		View view1 = mInflater.inflate(R.layout.listview_home1, null);
		initExamListView(view1);
		listViews.add(view1);
		View view2 = mInflater.inflate(R.layout.listview_home2, null);
		initQuestionListView(view2);
		listViews.add(view2);
		View view3 = mInflater.inflate(R.layout.listview_home3, null);
		initPieceListView(view3);
		listViews.add(view3);
		mPager.setAdapter(new MyPagerAdapter(listViews));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	private void initPieceListView(View view3) {
		// TODO Auto-generated method stub
		pieceXListView = (XListView) view3.findViewById(R.id.xlistView3);
		pieceXListView.setXListViewListener(this);
		ThreadUtils.executorService.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (CacheUtil.piecelist == null) {
					piecelist = ExamDB.getData(3);
					CacheUtil.piecelist = piecelist;
				} else {
					piecelist = CacheUtil.piecelist;
				}
				handler.sendEmptyMessage(3);
			}
		});

	}

	private void initQuestionListView(View view2) {
		// TODO Auto-generated method stub
		questionXListView = (XListView) view2.findViewById(R.id.xlistView2);
		questionXListView.setXListViewListener(this);
		ThreadUtils.executorService.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (CacheUtil.questionlist == null) {
					questionlist = ExamDB.getData(2);
					CacheUtil.questionlist = questionlist;
				} else {
					questionlist = CacheUtil.questionlist;
				}
				handler.sendEmptyMessage(2);
			}
		});

	}

	private void initExamListView(View view1) {
		// TODO Auto-generated method stub
		examXListView = (XListView) view1.findViewById(R.id.xlistView1);
		examXListView.setXListViewListener(this);
		ThreadUtils.executorService.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (CacheUtil.examlist == null) {
					examlist = ExamDB.getData(1);
					CacheUtil.examlist = examlist;
				} else {
					examlist = CacheUtil.examlist;
				}
				handler.sendEmptyMessage(1);
			}
		});
	}

	private void InitImageView(View view) {
		cursor = (ImageView) view.findViewById(R.id.cursor);
		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.a)
				.getWidth();// 获取图片宽度
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		offset = (screenW / 3 - bmpW + 10) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);// 设置动画初始位置
	}

	private void initTextView(View view) {
		// TODO Auto-generated method stub
		t1 = (TextView) view.findViewById(R.id.tab1Text);
		t2 = (TextView) view.findViewById(R.id.tab2Text);
		t3 = (TextView) view.findViewById(R.id.tab3Text);
		t1.setTextColor(getResources().getColor(R.color.main_back));
		t1.setOnClickListener(new Click(0));
		t2.setOnClickListener(new Click(1));
		t3.setOnClickListener(new Click(2));
	}

	private void getNewExamData() {
		UserCache.firstRun = false;
		long lastTime = preference.getLong("lastExamUpdate");
		long now = System.currentTimeMillis() / 1000;
		if (lastTime == 0) {
			examXListView.setRefreshTime("从未更新");
		} else {
			examXListView.setRefreshTime(setTime(now - lastTime));
		}
		preference.putLong("lastExamUpdate", now);
		List<BmobQuery<Examination>> queries = new ArrayList<BmobQuery<Examination>>();
		BmobQuery<Examination> query = new BmobQuery<Examination>();
		query.setLimit(20);
		query.order("-date");
		queries.add(query);
		if (UserCache.isLogin) {
			query = new BmobQuery<Examination>();
			query.addWhereEqualTo("school", UserCache.user.getSid());
			queries.add(query);
			if (UserCache.user.getMid() != 0) {
				query = new BmobQuery<Examination>();
				query.addWhereEqualTo("major", UserCache.user.getMid());
				queries.add(query);
			}
		}
		query = new BmobQuery<Examination>();
		query.addWhereGreaterThan("date", ExamDB.getNewestDate(1));
		queries.add(query);
		query = new BmobQuery<Examination>();
		query.addWhereEqualTo("type", 1);
		queries.add(query);
		query = new BmobQuery<Examination>();
		query.and(queries);
		query.findObjects(context, new FindListener<Examination>() {
			@Override
			public void onSuccess(List<Examination> arg0) {
				// TODO Auto-generated method stub
				int total = ExamDB.setData(context, arg0, 1);
				if (total != 0) {
					MToast.show(context, "更新" + total + "条记录");
				} else {
					MToast.show(context, "暂无更新");
				}
				examXListView.stopRefresh();
				examlist = ExamDB.getData(1);
				examAdapter = new ExamXListViewAdapter(getActivity(), examlist,
						examXListView);
				examXListView.setAdapter(examAdapter);
				examXListView.setFocusable(false);
			}

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stu
				examXListView.stopRefresh();
			}
		});
	}

	private void getNewQuestionData() {
		long lastTime = preference.getLong("lastQuestionUpdate");
		long now = System.currentTimeMillis() / 1000;
		if (lastTime == 0) {
			questionXListView.setRefreshTime("从未更新");
		} else {
			questionXListView.setRefreshTime(setTime(now - lastTime));
		}
		preference.putLong("lastQuestionUpdate", now);
		List<BmobQuery<Examination>> queries = new ArrayList<BmobQuery<Examination>>();
		BmobQuery<Examination> query = new BmobQuery<Examination>();
		query.setLimit(20);
		query.order("-date");
		queries.add(query);
		if (UserCache.isLogin) {
			if (UserCache.user.getMid() != 0) {
				query = new BmobQuery<Examination>();
				query.addWhereEqualTo("major", UserCache.user.getMid());
				queries.add(query);
			}
		}
		query = new BmobQuery<Examination>();
		query.addWhereGreaterThan("date", ExamDB.getNewestDate(2));
		queries.add(query);
		query = new BmobQuery<Examination>();
		query.addWhereEqualTo("type", 2);
		queries.add(query);
		query = new BmobQuery<Examination>();
		query.and(queries);
		query.findObjects(context, new FindListener<Examination>() {
			@Override
			public void onSuccess(List<Examination> arg0) {
				// TODO Auto-generated method stub
				int total = ExamDB.setData(context, arg0, 2);
				if (total != 0) {
					MToast.show(context, "更新" + total + "条记录");
				} else {
					MToast.show(context, "暂无更新");
				}
				questionXListView.stopRefresh();
				questionlist = ExamDB.getData(2);
				// adapter.notifyDataSetInvalidated();
				questionAdapter = new QuestionXListViewAdapter(getActivity(),
						questionlist, questionXListView);
				questionXListView.setAdapter(questionAdapter);
				questionXListView.setFocusable(false);
			}

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stu
			}
		});
	}

	private void getNewPieceData() {
		long lastTime = preference.getLong("lastPieceUpdate");
		long now = System.currentTimeMillis() / 1000;
		if (lastTime == 0) {
			pieceXListView.setRefreshTime("从未更新");
		} else {
			pieceXListView.setRefreshTime(setTime(now - lastTime));
		}
		preference.putLong("lastPieceUpdate", now);
		List<BmobQuery<Examination>> queries = new ArrayList<BmobQuery<Examination>>();
		BmobQuery<Examination> query = new BmobQuery<Examination>();
		query.setLimit(20);
		query.order("-date");
		queries.add(query);
		if (UserCache.isLogin) {
			query = new BmobQuery<Examination>();
			query.addWhereEqualTo("school", UserCache.user.getSid());
			queries.add(query);
			if (UserCache.user.getMid() != 0) {
				query = new BmobQuery<Examination>();
				query.addWhereEqualTo("major", UserCache.user.getMid());
				queries.add(query);
			}
		}
		query = new BmobQuery<Examination>();
		query.addWhereGreaterThan("date", ExamDB.getNewestDate(3));
		queries.add(query);
		query = new BmobQuery<Examination>();
		query.addWhereEqualTo("type", 3);
		queries.add(query);
		query = new BmobQuery<Examination>();
		query.and(queries);
		query.findObjects(context, new FindListener<Examination>() {
			@Override
			public void onSuccess(List<Examination> arg0) {
				// TODO Auto-generated method stub
				int total = ExamDB.setData(context, arg0, 3);
				if (total != 0) {
					MToast.show(context, "更新" + total + "条记录");
				} else {
					MToast.show(context, "暂无更新");
				}
				pieceXListView.stopRefresh();
				piecelist = ExamDB.getData(3);
				pieceAdapter = new PieceXListViewAdapter(getActivity(),
						piecelist, pieceXListView);
				pieceXListView.setAdapter(pieceAdapter);
				pieceXListView.setFocusable(false);
			}

			@Override
			public void onError(int arg0, String arg1) {
				// TODO Auto-generated method stu
				pieceXListView.stopRefresh();
			}
		});
	}

	private String setTime(long l) {
		// TODO Auto-generated method stub
		if (l < 60) {

			return l + "秒前";
		}
		l = l / 60;
		if (l < 60) {

			return l + "分钟前";
		}
		l = l / 60;
		if (l < 24) {
			return l + "小时前";
		}
		l = l / 24;
		if (l < 30) {
			return l + "天前";
		}
		l = l / 30;
		if (l < 12) {
			return l + "个月前";
		}
		return l + "年前";
	}

	public class Click implements OnClickListener {
		private int i = 0;

		public Click(int i) {
			this.i = i;
		}

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			mPager.setCurrentItem(i);
		}

	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量

		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			t1.setTextColor(Color.rgb(90, 90, 90));
			t2.setTextColor(Color.rgb(90, 90, 90));
			t3.setTextColor(Color.rgb(90, 90, 90));
			switch (arg0) {
			case 0:
				t1.setTextColor(getResources().getColor(R.color.main_back));
				if (currIndex == 1) {
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, 0, 0, 0);
				}
				break;

			case 1:
				MLog.i("a:" + 1);
				t2.setTextColor(getResources().getColor(R.color.main_back));
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, one, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, one, 0, 0);
				}
				break;
			case 2:
				MLog.i("a:" + 2);
				t3.setTextColor(getResources().getColor(R.color.main_back));
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, two, 0, 0);
				} else if (currIndex == 1) {
					animation = new TranslateAnimation(one, two, 0, 0);
				}
				break;
			default:

				break;

			}
			MLog.i("a:" + arg0);
			if (animation == null) {
				return;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(100);
			cursor.startAnimation(animation);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		switch (mPager.getCurrentItem()) {
		case 0:
			getNewExamData();
			break;
		case 1:
			getNewQuestionData();
			break;
		case 2:
			getNewPieceData();
		default:
			break;
		}

	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				examAdapter = new ExamXListViewAdapter(getActivity(), examlist,
						examXListView);
				examXListView.setAdapter(examAdapter);
				break;
			case 2:
				questionAdapter = new QuestionXListViewAdapter(getActivity(),
						questionlist, questionXListView);
				questionXListView.setAdapter(questionAdapter);
				break;
			case 3:
				pieceAdapter = new PieceXListViewAdapter(getActivity(),
						piecelist, pieceXListView);
				pieceXListView.setAdapter(pieceAdapter);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		context.unregisterReceiver(complete);
	}

	public class ReleaseComplete extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals("releaseComplete")) {
				getNewExamData();
			} else if (intent.getAction().equals("finishDownload")) {
				getNewExamData();
			}
		}
	}
}
